package com.jdone.compus.service;

import com.jdone.compus.model.BlowAnnouncement;
import com.jdone.compus.repository.BlowAnnouncementRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public class BlowAnnouncementService {

    @Autowired
    private BlowAnnouncementRepository repository;

    /** 新增公告，默认启用状态为 false */
    public BlowAnnouncement create(BlowAnnouncement dto) {
        dto.setEnabled(false);
        return repository.save(dto);
    }

    /** 根据ID查询公告 */
    public BlowAnnouncement getById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new RuntimeException("公告未找到"));
    }

    /** 分页查询所有公告 */
    public Page<BlowAnnouncement> getAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    /** 更新公告；如果将 enabled 变为 true，确保仅此一条为 true */
    @Transactional
    public BlowAnnouncement update(Long id, BlowAnnouncement dto) {
        BlowAnnouncement entity = getById(id);
        // 如果请求开启此公告
        if (dto.getEnabled() != null && dto.getEnabled()) {
            // 将其他已启用的公告置为 false
            List<BlowAnnouncement> enabledList = repository.findByEnabledTrue();
            for (BlowAnnouncement other : enabledList) {
                if (!other.getId().equals(id)) {
                    other.setEnabled(false);
                    repository.save(other);
                }
            }
            entity.setEnabled(true);
        } else if (dto.getEnabled() != null) {
            entity.setEnabled(false);
        }
        // 更新内容字段
        if (dto.getContent() != null) {
            entity.setContent(dto.getContent());
        }
        return repository.save(entity);
    }

    /** 删除公告 */
    public void delete(Long id) {
        BlowAnnouncement entity = getById(id);
        repository.delete(entity);
    }

    /** 查询当前启用的唯一公告 */
    public BlowAnnouncement getEnabledAnnouncement() {
        List<BlowAnnouncement> list = repository.findByEnabledTrue();
        if (list.isEmpty()) {
            throw new RuntimeException("未找到启用的公告");
        }
        return list.get(0);
    }
}

